<template>
  <div class="mydig">
    <el-dialog :title="`为【${username}】分配权限`" :visible="show">
      <el-tree
        ref="mytree"
        check-strictly
        default-expand-all
        :props="{ label: 'name' }"
        :data="perList"
        show-checkbox
        node-key="id"
      >
      </el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllPermissionApi } from '@/api/permission'
import { getRoleDetailApi, setRoleApi } from '@/api/setting'
export default {
  props: ['show', 'username'],
  data () {
    return {
      perList: [],
      checkList: [],
      permIds: [],
      id: ''
    }
  },
  methods: {
    async getAllPermission () {
      const res = await getAllPermissionApi()
      //   console.log(res)
      this.perList = this.turnData(res.data, '0')
    },
    turnData (arr, pid) {
      const newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const children = this.turnData(arr, item.id)
          if (children.length > 0) {
            item.children = children
          }
          newArr.push(item)
        }
      })
      return newArr
    },
    cancel () {
      this.$emit('update:show', false)
    },
    async submit () {
      const res = this.$refs.mytree.getCheckedKeys()
      //console.log(res);
      try {
        await setRoleApi({
          id: this.id,
          permIds: res
        })

        this.$message.success('更新成功')
        this.$emit('update:show', false)
      } catch (error) {
        console.log(error)
      }
    },
    async getRoleDetail (id) {
      this.id = id
      const res = await getRoleDetailApi(id)
      // console.log(res);
      this.permIds = res.data.permIds
      this.$refs.mytree.setCheckedKeys(this.permIds)
    }
  }
}
</script>

<style lang="scss" scoped>
.mydig {
  ::v-deep.el-tree-node__content {
    height: 36px;
  }
}
</style>
